#include "utils.h"
#include <iostream>
#include <fstream>
#include <ctime>

void initialize_system() {
    std::cout << "Initializing system..." << std::endl;
    load_config();
    log_message("System initialized successfully");
}

void cleanup_system() {
    std::cout << "Cleaning up system..." << std::endl;
    save_config();
    log_message("System cleanup completed");
}

void display_result(const char* operation, int value) {
    std::cout << operation << ": " << value << std::endl;
    
    char buffer[256];
    sprintf(buffer, "%s result: %d", operation, value);
    log_message(buffer);
}

void display_result(const char* operation, double value) {
    std::cout << operation << ": " << value << std::endl;
    
    char buffer[256];
    sprintf(buffer, "%s result: %.2f", operation, value);
    log_message(buffer);
}

void load_config() {
    std::ifstream config_file("config.txt");
    if (config_file.is_open()) {
        log_message("Configuration loaded successfully");
        config_file.close();
    } else {
        log_error("Failed to load configuration file");
    }
}

void save_config() {
    std::ofstream config_file("config.txt");
    if (config_file.is_open()) {
        config_file << "# Calculator Configuration" << std::endl;
        config_file << "precision=2" << std::endl;
        config_file.close();
        log_message("Configuration saved successfully");
    } else {
        log_error("Failed to save configuration file");
    }
}

void log_message(const char* message) {
    std::time_t now = std::time(0);
    char* timestr = std::ctime(&now);
    timestr[strlen(timestr) - 1] = '\0'; // Remove newline
    
    std::cout << "[" << timestr << "] INFO: " << message << std::endl;
}

void log_error(const char* error) {
    std::time_t now = std::time(0);
    char* timestr = std::ctime(&now);
    timestr[strlen(timestr) - 1] = '\0'; // Remove newline
    
    std::cerr << "[" << timestr << "] ERROR: " << error << std::endl;
}
